package com.situ.skymall.user.api.controller;

import com.situ.model.Account;
import com.situ.model.User;
import com.situ.service.UserService;
import com.situ.utils.JsonResult;
import com.situ.utils.JwtUtils;
import com.wf.captcha.SpecCaptcha;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.jasypt.util.password.StrongPasswordEncryptor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.io.IOException;
import java.time.Duration;
import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@RestController
@RequestMapping("/api/v1/login")
public class LoginController {

    private UserService userService;
    private RedisTemplate<Object, Object> redisTemplate;
    private final StrongPasswordEncryptor PE = new StrongPasswordEncryptor();

    @Value("${jwt.secret}")
    private String jwtSecret;

    @Autowired
    public void setUserService(UserService userService) {
        this.userService = userService;
    }

    @Autowired
    public void setRedisTemplate(RedisTemplate<Object, Object> redisTemplate) {
        this.redisTemplate = redisTemplate;
    }


    /**
     * 用户注册
     */
    @PostMapping("/register")
    public JsonResult<?> register(@RequestBody User user) {
        try {
            // 检查用户名是否已存在
            User existUser = userService.findByUsername(user.getUsername());
            if (existUser != null) {
                return JsonResult.fail("用户名已存在");
            }
            // 密码加密
            user.setPassword(PE.encryptPassword(user.getPassword()));
            // 设置默认值
            user.setStatus(1);
            user.setIsDelete(0);
            user.setRoleType(1);
            user.setCreatedAt(LocalDateTime.now());
            user.setUpdatedAt(LocalDateTime.now());

            boolean result = userService.save(user);
            if (result) {
                return JsonResult.success("注册成功");
            } else {
                return JsonResult.fail("注册失败");
            }
        } catch (Exception e) {
            return JsonResult.fail(500, "注册过程中发生错误");
        }
    }

    /**
     * 用户登录
     */
    @PostMapping()
    public JsonResult<?> login(@RequestBody Account account) {
        try {
//            // 验证码校验
//            String redisKey = "captcha-" + account.getCaptchaId();
//            System.out.println("查询Redis的键名: " + redisKey);
//            String correct = (String) redisTemplate.opsForValue().get(redisKey);
//            System.out.println("Redis中的验证码: " + correct);
//            System.out.println("用户输入的验证码: " + account.getCaptcha());
//            if (correct == null) {
//                return JsonResult.fail("验证码已过期");
//            }
//            if (!correct.equalsIgnoreCase(account.getCaptcha())) {
//                return JsonResult.fail("验证码错误");
//            }
//
//            // 验证成功后，立即删除验证码，防止重复使用
//            redisTemplate.delete("captcha-" + account.getCaptchaId());

            // 用户名密码校验
            User user = userService.findByUsername(account.getUsername());
            if (user == null){
                return JsonResult.fail("用户不存在");
            }

            boolean pass = PE.checkPassword(account.getPassword(), user.getPassword());
            if (!pass) {
                return JsonResult.fail("密码不正确");
            }

            // 检查用户状态
            if (user.getStatus() != 1) {
                return JsonResult.fail("用户已被禁用");
            }

            //生成带有 scope 的JWT
            Map<String, Object> claims = new HashMap<>();
            claims.put("userId", String.valueOf(user.getId()));
            // 为了与Admin服务的JWT保持一致，将用户名统一放到'name'字段
            claims.put("name", user.getUsername());
            claims.put("scope", "USER"); // 添加角色范围声明

            String jwt = JwtUtils.createJwt(UUID.randomUUID().toString(), user.getPhone(),
                    claims, LocalDateTime.now().plusHours(24), jwtSecret); // 用户token有效期可以长一些

            Map<String, Object> responseData = new HashMap<>();
            responseData.put("token", jwt);
            responseData.put("user", user);

            return JsonResult.success(responseData);
        } catch (Exception e) {
            System.err.println("登录时发生严重错误，详细信息如下:");
            e.printStackTrace();

            // 返回给前端的依然是通用错误信息，但我们可以在后端日志中看到具体原因
            return JsonResult.fail(500, "登录过程中发生错误，请联系管理员");
        }
    }


//
//    /**
//     * 获取验证码
//     */
//    @GetMapping("/captcha")
//    public void captcha(@RequestParam(required = false) String id,
//                        HttpServletResponse resp,
//                        HttpServletRequest req) {
//        try {
//            // 如果没有提供id，生成一个随机id
//            String captchaId = (id != null) ? id : UUID.randomUUID().toString();
//
//            SpecCaptcha captcha = new SpecCaptcha(140, 40, 4);
//
//            // 设置响应头
//            resp.setContentType("image/png");
//            resp.setHeader("Pragma", "No-cache");
//            resp.setHeader("Cache-Control", "no-cache");
//            resp.setDateHeader("Expires", 0);
//
//            // 存储到Redis
//            redisTemplate.opsForValue().set("captcha-" + captchaId,
//                    captcha.text().toLowerCase(), Duration.ofMinutes(3));
//
//            System.out.println("验证码文本: " + captcha.text());
//            System.out.println("验证码id: " +"captcha-"  + captchaId);
//            // 输出验证码图片
//            captcha.out(resp.getOutputStream());
//
//        } catch (Exception e) {
//            System.err.println("生成验证码时发生错误: " + e.getMessage());
//            e.printStackTrace();
//
//            try {
//                resp.sendError(HttpServletResponse.SC_INTERNAL_SERVER_ERROR, "验证码生成失败");
//            } catch (IOException ioException) {
//                System.err.println("发送错误响应失败: " + ioException.getMessage());
//            }
//        }
//    }


}
